<template>
  <div class="config-container">
    <!-- 页面标题 -->
    <el-card class="page-header-card" shadow="never">
      <div class="page-header">
        <h2 class="page-title">网站配置</h2>
        <p class="page-subtitle">管理系统的基本信息、作者信息、社交链接等配置</p>
      </div>
    </el-card>

    <!-- 配置内容 -->
    <el-card class="config-content-card" shadow="hover">
      <el-tabs v-model="activeTab" class="config-tabs">
        <!-- 基本信息 Tab -->
        <el-tab-pane name="basic" class="tab-pane">
          <template #label>
            <div class="tab-label-content">
              <el-icon class="tab-icon"><Setting /></el-icon>
              <span class="tab-label">基本信息</span>
            </div>
          </template>
          <div class="tab-content">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="config-form">
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="网站Logo" prop="logo">
                    <div class="upload-wrapper">
                      <el-upload
                        class="avatar-uploader"
                        :http-request="logoUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >
                        <img v-if="form.logo" :src="form.logo" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                      </el-upload>
                      <div class="upload-tip">建议尺寸：200x200像素</div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="网站名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入网站名称" class="form-input" />
                  </el-form-item>
                  <el-form-item label="网站介绍" prop="summary">
                    <el-input v-model="form.summary" type="textarea" placeholder="请输入网站介绍" :rows="3" class="form-textarea" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="备案号" prop="recordNum">
                    <el-input v-model="form.recordNum" placeholder="请输入备案号" class="form-input" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="网站地址" prop="webUrl">
                    <el-input v-model="form.webUrl" placeholder="请输入网站地址" class="form-input" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 作者信息 Tab -->
        <el-tab-pane name="author" class="tab-pane">
          <template #label>
            <div class="tab-label-content">
              <el-icon class="tab-icon"><User /></el-icon>
              <span class="tab-label">作者信息</span>
            </div>
          </template>
          <div class="tab-content">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="config-form">
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="作者头像" prop="authorAvatar">
                    <div class="upload-wrapper">
                      <el-upload
                        class="avatar-uploader"
                        :http-request="authorAvatarUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >
                        <img v-if="form.authorAvatar" :src="form.authorAvatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                      </el-upload>
                      <div class="upload-tip">建议尺寸：200x200像素</div>
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="作者名称" prop="author">
                    <el-input v-model="form.author" placeholder="请输入作者名称" class="form-input" />
                  </el-form-item>
                  <el-form-item label="个性签名" prop="authorInfo">
                    <el-input v-model="form.authorInfo" placeholder="请输入个性签名" class="form-input" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="24">
                  <el-form-item label="关于我" prop="aboutMe">
                    <div class="editor-wrapper">
                      <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
                      <Editor style="overflow-y: hidden; min-height: 300px;" v-model="form.aboutMe" :defaultConfig="editorConfig" :mode="mode"
                        @onCreated="handleCreated"/>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 社交信息 Tab -->
        <el-tab-pane name="social" class="tab-pane">
          <template #label>
            <div class="tab-label-content">
              <el-icon class="tab-icon"><Share /></el-icon>
              <span class="tab-label">社交信息</span>
            </div>
          </template>
          <div class="tab-content">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="config-form">
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="Github地址" prop="github">
                    <el-input v-model="form.github" placeholder="请输入Github地址" class="form-input">
                      <template #prefix>
                        <el-icon><ElementPlus /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="Gitee地址" prop="gitee">
                    <el-input v-model="form.gitee" placeholder="请输入Gitee地址" class="form-input">
                      <template #prefix>
                        <el-icon><Platform /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="QQ号" prop="qqNumber">
                    <el-input v-model="form.qqNumber" placeholder="请输入QQ号" class="form-input">
                      <template #prefix>
                        <el-icon><ChatDotRound /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="QQ群" prop="qqGroup">
                    <el-input v-model="form.qqGroup" placeholder="请输入QQ群" class="form-input">
                      <template #prefix>
                        <el-icon><User /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="微信" prop="wechat">
                    <el-input v-model="form.wechat" placeholder="请输入微信号" class="form-input">
                      <template #prefix>
                        <el-icon><ChatLineRound /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱地址" class="form-input">
                      <template #prefix>
                        <el-icon><Message /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 网站设置 Tab -->
        <el-tab-pane name="settings" class="tab-pane">
          <template #label>
            <div class="tab-label-content">
              <el-icon class="tab-icon"><Tools /></el-icon>
              <span class="tab-label">网站设置</span>
            </div>
          </template>
          <div class="tab-content">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="config-form">
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="游客头像" prop="touristAvatar">
                    <div class="upload-wrapper">
                      <el-upload
                        class="avatar-uploader"
                        :http-request="tourAvatarUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                      >
                        <img v-if="form.touristAvatar" :src="form.touristAvatar" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                      </el-upload>
                      <div class="upload-tip">建议尺寸：200x200像素</div>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="开启评论">
                    <el-switch 
                      v-model="form.openComment" 
                      :active-value="1" 
                      :inactive-value="0" 
                      @change="handleCommentSwitchChange"
                      class="config-switch"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 底部按钮 -->
      <div class="bottom-buttons">
        <el-button type="primary" class="save-btn" @click="submitForm">
          <el-icon><Check /></el-icon>
          保存配置
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, shallowRef, getCurrentInstance, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getWebConfigApi, updateWebConfigApi } from '@/api/website/config'
import {upload} from "@/api/systemArticle/article"
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { uploadLogo,uploadAuthorAvatar,updateCommentSwitchApi,uploadTourAvatar } from '@/api/website/config'


// 添加处理评论开关变化的函数
const handleCommentSwitchChange = (value: number) => {
  console.log('评论开关状态变化:', value)
  // 在这里添加你需要的逻辑处理
  updateCommentSwitchApi({ openComment: value }).then(response => {
    ElMessage.success('更新成功')
  })
}

// 添加处理上传成功的函数
const handleAvatarSuccess = (response: any, file: any) => {
  console.log('上传成功:', response, file)
  ElMessage.success('上传成功')
}

const tourAvatarUpload = (options: any) => {
  const { file, onSuccess, onError } = options
  
  // 调用上传API
  upload(file)
    .then(response => {
      console.log('上传响应:', response)
      if (response.code === 200) { // 根据实际返回状态码调整
        // 保存返回的图片URL到表单中
        form.value.touristAvatar = response.data
        uploadTourAvatar(response.data)
        onSuccess(response)
        ElMessage.success('上传成功')
      } else {
        ElMessage.error(response.msg || '上传失败')
        onError(new Error(response.msg || '上传失败'))
      }
    })
    .catch(error => {
      console.error('上传错误:', error)
      ElMessage.error('上传失败: ' + (error.message || '网络错误'))
      onError(error)
    })
}

const authorAvatarUpload = (options: any) => {
  const { file, onSuccess, onError } = options
  
  // 调用上传API
  upload(file)
    .then(response => {
      console.log('上传响应:', response)
      if (response.code === 200) { // 根据实际返回状态码调整
        // 保存返回的图片URL到表单中
        form.value.authorAvatar = response.data
        uploadAuthorAvatar(response.data)
        onSuccess(response)
        ElMessage.success('上传成功')
      } else {
        ElMessage.error(response.msg || '上传失败')
        onError(new Error(response.msg || '上传失败'))
      }
    })
    .catch(error => {
      console.error('上传错误:', error)
      ElMessage.error('上传失败: ' + (error.message || '网络错误'))
      onError(error)
    })
}

const logoUpload = (options: any) => {
  const { file, onSuccess, onError } = options
  
  // 调用上传API
  upload(file)
    .then(response => {
      console.log('上传响应:', response)
      if (response.code === 200) { // 根据实际返回状态码调整
        // 保存返回的图片URL到表单中
        form.value.logo = response.data
        uploadLogo(response.data)
        onSuccess(response)
        ElMessage.success('上传成功')
      } else {
        ElMessage.error(response.msg || '上传失败')
        onError(new Error(response.msg || '上传失败'))
      }
    })
    .catch(error => {
      console.error('上传错误:', error)
      ElMessage.error('上传失败: ' + (error.message || '网络错误'))
      onError(error)
    })
}

const beforeAvatarUpload = (rawFile: any) => {
  // if (rawFile.type !== 'image/jpeg') {
  //   ElMessage.error('Avatar picture must be JPG format!')
  //   return false
  // } else 
  if (rawFile.size / 1024 / 1024 > 5) {
    ElMessage.error('图片过大，请换一张')
    return false
  }
  return true
}

const editorRef = shallowRef()
const mode = 'default'
const toolbarConfig = {}
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    // 配置上传图片
    uploadImage: {
      customUpload: contentUpload,
    },

    codeSelectLang: {
      // 代码语言
      codeLangs: [
        { text: "CSS", value: "css" },
        { text: "HTML", value: "html" },
        { text: "XML", value: "xml" },
        { text: "Java", value: "java" },
        // 其他
      ],
    },
  },
}


const activeTab = ref('basic')
const formRef = ref<FormInstance>()
const form = ref({
  logo: '',
  name: '',
  summary: '',
  recordNum: '',
  webUrl: '',
  author: '',
  authorInfo: '',
  authorAvatar: '',
  github: '',
  gitee: '',
  qqNumber: '',
  qqGroup: '',
  wechat: '',
  email: '',
  aliPay: '',
  weixinPay: '',
  showList: '',
  loginTypeList: '',
  openComment: 1,
  openAdmiration: 1,
  touristAvatar: '',
  bulletin: '',
  aboutMe: '',
  openLantern: 0
})
const showList = ref([])
const loginTypeList = ref([])
const loginTypes = ref<any>([])

const files = ref();

const rules = {
  name: [{ required: true, message: '请输入网站名称', trigger: 'blur' }],
  logo: [{ required: true, message: '请上传网站Logo', trigger: 'change' }],
  summary: [{ required: true, message: '请输入网站介绍', trigger: 'blur' }],
  // recordNum: [{ required: true, message: '请输入备案号', trigger: 'blur' }],
  author: [{ required: true, message: '请输入作者名称', trigger: 'blur' }]
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid) => {
    if (valid) {
      form.value.showList = JSON.stringify(showList.value)
      form.value.loginTypeList = JSON.stringify(loginTypeList.value)
      updateWebConfigApi(form.value).then(() => {
        ElMessage.success('保存成功')
      })
    }
  })
}
// 获取字典数据
const getDictDataByDictTypes = async () => {
  const res = await getDictDataByDictTypesApi(['login_type'])
  loginTypes.value = res.data.login_type.list
}

const handleCreated = (editor:any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//编辑器上传图片
function contentUpload(file: any, insertFn: any) {
  files.value = file;
  // FormData 对象
  var formData = new FormData();
  // 文件对象
  formData.append("file", files.value);
  upload(formData).then((res: any) => {
    insertFn(res.data, "", res.data);
  });
}

onMounted(() => {
  getWebConfigApi().then((res) => {
    form.value = res.data
    if (form.value.showList) {
      showList.value = JSON.parse(form.value.showList)
    }
    if (form.value.loginTypeList) {
      loginTypeList.value = JSON.parse(form.value.loginTypeList)
    }
  })

  getDictDataByDictTypes();
})
</script>

<style scoped>
.config-container {
  background: #f0f2f5;
  padding: 20px;
  min-height: calc(100vh - 84px);
}

.page-header-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.page-header {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #2d3a4f;
  margin: 0 0 10px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #8492a6;
  margin: 0;
}

.config-content-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.config-tabs {
  padding: 20px;
}

.config-tabs :deep(.el-tabs__header) {
  margin-bottom: 30px;
}

.config-tabs :deep(.el-tabs__nav-wrap)::after {
  height: 1px;
}

.config-tabs :deep(.el-tabs__item) {
  padding: 0 30px;
  height: 50px;
  font-size: 15px;
  font-weight: 500;
  color: #606266;
}

.config-tabs :deep(.el-tabs__item.is-active) {
  color: #409eff;
  font-weight: 600;
}

.config-tabs :deep(.el-tabs__active-bar) {
  height: 3px;
  border-radius: 2px;
}

.tab-label-content {
  display: flex;
  align-items: center;
  padding: 0 10px;
}

.tab-icon {
  margin-right: 8px;
  font-size: 16px;
}

.tab-content {
  padding: 0 20px;
}

.config-form {
  max-width: 100%;
}

.config-form :deep(.el-form-item) {
  margin-bottom: 25px;
}

.config-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #515a6e;
  font-size: 14px;
}

.form-input,
.form-textarea {
  width: 100%;
}

.upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 10px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
  background: #f0f8ff;
}

.el-icon.avatar-uploader-icon {
  font-size: 36px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
  border-radius: 10px;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: #8492a6;
}

.editor-wrapper {
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
}

.config-switch :deep(.el-switch__core) {
  width: 40px !important;
  height: 20px;
}

.config-switch :deep(.el-switch__core::after) {
  width: 16px;
  height: 16px;
}

.bottom-buttons {
  margin-top: 30px;
  padding: 20px;
  text-align: center;
  border-top: 1px solid #ebeef5;
}

.save-btn {
  padding: 12px 30px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 8px;
  background: #409eff;
  border: none;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.save-btn:hover {
  background: #66b1ff;
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(64, 158, 255, 0.4);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .config-container {
    padding: 15px;
  }
  
  .config-content-card {
    padding: 15px;
  }
  
  .config-tabs :deep(.el-tabs__item) {
    padding: 0 20px;
    font-size: 14px;
  }
  
  .tab-content {
    padding: 0 10px;
  }
}

@media (max-width: 992px) {
  .config-form :deep(.el-col) {
    margin-bottom: 20px;
  }
  
  .avatar-uploader .el-upload {
    width: 140px;
    height: 140px;
  }
  
  .el-icon.avatar-uploader-icon {
    width: 140px;
    height: 140px;
  }
  
  .avatar {
    width: 140px;
    height: 140px;
  }
}

@media (max-width: 768px) {
  .config-container {
    padding: 10px;
  }
  
  .page-header {
    padding: 15px;
  }
  
  .page-title {
    font-size: 20px;
  }
  
  .config-content-card {
    padding: 10px;
  }
  
  .config-tabs {
    padding: 15px;
  }
  
  .config-tabs :deep(.el-tabs__item) {
    padding: 0 15px;
    font-size: 13px;
  }
  
  .tab-content {
    padding: 0;
  }
  
  .config-form :deep(.el-form-item__label) {
    font-size: 13px;
  }
  
  .bottom-buttons {
    padding: 15px;
  }
  
  .save-btn {
    padding: 10px 20px;
    font-size: 13px;
  }
}
</style>
